<?php
/**
 @prefix : <http://purl.org/net/ns/doas#> .
 @about: "<app/controllers/article_controller.php>", a: ":PHPScript",
 :shortdesc "This is a MML Tracks placeholder class.";
 :author [:name "Logue"; :homepage <http://logue.be/> ];
 :license <http://www.gnu.org/licenses/gpl-3.0.html>;
 :dependencies "none" .
*/
// Lorelei MML Tracks placeholder class
// Copyright (c)2008 Logue <http://logue.be/> All rights reserved.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

class MmlsController extends AppController {

	var $name = 'Mmls';
	var $helpers = array('Html', 'Form');

	function beforeFilter(){
		parent::beforeFilter();
		if ($this->layout == 'ajax') {
			Configure::write('debug', 0);
		} else {
			parent::beforeRender();
		}
		//ログインを必要としない処理 指定しないと全てのactionでログインが必要となるので注意
		$this->Auth->allow('play','concert','composer','mml','export','jsmml');
		$auth = $this->Auth->user();	// セッション読み込み
		$this->set('auth',$auth);
	}

	function add($article_id=null) {
		if (!$article_id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('controller'=>'articles','action'=>'view','id'=>$article_id));
		}
		$auth = $this->Auth->user();
		if (!$auth['User']['id']){
			$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Edit',true),__('MML Track',true)));
			$this->redirect(array('controller'=>'article','action'=>'view','id'=>$this->data['Mml']['article_id']));
		}
		if (!empty($this->data)) {
			$this->Mml->create();
			if ($this->Mml->validates()) {
				$this->data['Mml']['ch1'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch1']);
				$this->data['Mml']['ch2'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch2']);
				$this->data['Mml']['ch3'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch3']);

				// 保存処理
				if ($this->Mml->save($this->data)) {
					$this->Session->setFlash(sprintf(__('The %s has been saved.',true), __('MML Track',true)));
					$this->redirect(array('controller'=>'articles','action'=>'view',$this->data['Mml']['article_id']));
				} else {
					$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.',true), __('MML Track',true)));
					pr($this->data);
				}
			}else{
				$this->Session->setFlash(__('The wrong value is included.',true));	// データーバリテーション
			}
		}
		// 楽器一覧を読み込み
		$this->set('instruments', $this->Mml->Instrument->find('list'));
		$this->set('ranks', $this->Mml->Rank->find('list'));
		$this->set('article_id',$article_id);
		$this->set('article',$this->Mml->Article->findById($article_id));
	}

	function edit($id=null) {
		// ページタイトルの修正
		$this->pageTitle = sprintf(__('Edit %s',true),__('MML Track',true));

		// 存在するか？
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('MML Track',false)));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			// ユーザチェック
			$auth = $this->Auth->user();
			if ($auth['User']['id'] != $this->data['Mml']['user_id']){
				$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Edit',true),__('MML Track',true)));
				$this->redirect(array('controller'=>'article','action'=>'view','id'=>$this->data['Mml']['article_id']));
			}
			if ($this->Mml->validates()) {
				$this->data['Mml']['ch1'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch1']);
				$this->data['Mml']['ch2'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch2']);
				$this->data['Mml']['ch3'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch3']);
				
				// 保存処理
				if ($this->Mml->save($this->data)) {
					$this->Session->setFlash(sprintf(__('The %s has been saved.',true), __('MML Track',true)));
					$this->redirect(array('controller'=>'articles','action'=>'view',$this->data['Mml']['article_id']));
				} else {
					$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.',true), __('MML Track',true)));
				}
			}else{
				$this->Session->setFlash(__('The wrong value is included.',true));	// データーバリテーション
			}
		}else{
			// 読み込み
			$this->data = $this->Mml->read(null, $id);
		}

		$this->set('mml', $this->data);
		// 楽器一覧を読み込み
		$this->set('instruments', $this->Mml->Instrument->find('list'));
		$this->set('ranks', $this->Mml->Rank->find('list'));
	}

	function delete($id = null) {
		
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('MML Track',false)));
			$this->redirect(array('controller'=>'articles','action'=>'index'));
		}
		$mml = $this->Mml->read(null, $id);
		$article_id = $mml['Mml']['article_id'];
		
		$auth = $this->Auth->user();
		if ($auth['User']['id'] != $mml['Mml']['user_id']){
			$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Delete',true),__('MML Track',true)));
			$this->redirect(array('controller'=>'articles','action'=>'view','id'=>$article_id));
		}else{
			if ($this->Mml->del($id)) {
				$this->Session->setFlash(sprintf(__('The %s has been deleted.',true), __('MML Track',false)));
				$this->redirect(array('controller'=>'articles','action'=>'view','id'=>$article_id));
			}
		}
	}

/**************************************************************************************************/
	function admin_index() {
		$this->Mml->recursive = 0;
		$this->set('mmls', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('MML Track',false)));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('mml', $this->Mml->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->Mml->create();
			if ($this->Mml->save($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved.', true), __('MML Track',true)));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('MML Track',true)));
			}
		}
		$articles = $this->Mml->Article->find('list');
		$users = $this->Mml->User->find('list');
		$instruments = $this->Mml->Instrument->find('list');
		$this->set(compact('articles', 'users', 'instruments'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('MML Track',false)));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Mml->save($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved.', true), __('MML Track',true)));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('MML Track',true)));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Mml->read(null, $id);
		}
		$articles = $this->Mml->Article->find('list');
		$users = $this->Mml->User->find('list');
		$instruments = $this->Mml->Instrument->find('list');
		$this->set(compact('articles','users','instruments'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('MML Track',false)));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Mml->del($id)) {
			$this->Session->setFlash(sprintf(__('The %s has been deleted.',true), __('MML Track',false)));
			$this->redirect(array('action'=>'index'));
		}
	}

/**************************************************************************************************/
// エクスポート処理

	// 単一トラック
	function mml($id,$type = 'mml'){
		$this->layout = 'ajax';
		$referer = $this->referer();
		if ($id && !($referer && ereg("http://",$referer) && !(ereg("mabinogi.logue.be",$referer) || ereg("localhost",$referer))) ) $mml = $this->Mml->read(null, $id);
		
		if (empty($mml)){
			header("HTTP/1.0 404 Not Found");
			$error = array(
				'Mml'=>array(
					'name'=>'ERROR!',
					'ch1'=>'t150v15l16o2cbc-a+cbc-a+cbc-a+cbc-a+er8.f32f+32<a+',
					'ch2'=>'l16rv7o2cbc-a+cbc-a+cbc-a+cbc-a+e4f32f+32<a+',
					'ch3'=>'l16rv15o1bra+rbra+rbra+rbra+e4l32ff+',
					'pan'=>'64'
				),
				'Article'=>array('title'=>'Lorelei MML Exporter error!'),
				'User'=>array('username'=>'Lorelei')
			);
			$instrument = $this->Mml->Instrument->find(array('Instrument.id'=>1));
			$mml = array_merge($error,$instrument);
		}

		if ($type == 'json') $mml = json_encode($mml);	// Jsonで出力
		$this->set('mml', $mml);
		$this->render($type);
	}

	// 一括エクスポート
	function export($id=null,$type='midi'){
		$this->layout = 'ajax';

		// リファラーキック
		$referer = $this->referer();
		if ($id && !($referer && ereg("http://",$referer) && (ereg("mabinogi.logue.be",$referer) || ereg("localhost",$referer))) ) 
			$mmls = $this->Mml->find('all',array(
				'conditions' => array('Mml.article_id'=>$id)
			));
		if (empty($mmls)){
			header("HTTP/1.0 403 Forbidden");
			$error = array(
				'Mml'=>array(
					'name'=>'ERROR!',
					'ch1'=>'t150v15l16o2cbc-a+cbc-a+cbc-a+cbc-a+er8.f32f+32<a+',
					'ch2'=>'l16rv7o2cbc-a+cbc-a+cbc-a+cbc-a+e4f32f+32<a+',
					'ch3'=>'l16rv15o1bra+rbra+rbra+rbra+e4l32ff+',
					'pan'=>'64'
				),
				'Article'=>array('title'=>'Lorelei MML Exporter error!'),
				'User'=>array('username'=>'Lorelei')
			);
			$instrument = $this->Mml->Instrument->find(array('Instrument.id'=>1));
			$mml = array_merge($error,$instrument);
			$mmls[0] = $mml; 
		}
		
		if ($type == 'json') $mmls = json_encode($mmls);	// Jsonで出力
		$this->set('mmls', $mmls);
		$this->render($type);
	}

	function concert($id) {
		$this->setAction('export',$id,'midi');
	}

	function play($id = null){
		$this->setAction('mml',$id,'midi');
	}

/*************************************************************************************************/
	function composer(){
		if (!empty($this->params['url']['q'])) {
			$referer = $this->referer();
			$this->layout = 'ajax';
			if (ereg("http://",$referer) && !(ereg("mabinogi.logue.be",$referer) || ereg("localhost",$referer)) ){
				$mml = array(
					'Mml'=>array(
						'name'=>'ERROR!',
						'ch1'=>'t150v15l16<cbc-a+cbc-a+cbc-a+cbc-a+er8.f32f+32<a+',
						'ch2'=>'l16rv7<cbc-a+cbc-a+cbc-a+cbc-a+e4f32f+32<a+',
						'ch3'=>'l16rv15o2bra+rbra+rbra+rbra+e4l32ff+',
						'pan'=>'64'
					),
					'Article'=>array('title'=>'Lorelei MML Composer error!'),
					'User'=>array('username'=>'Lorelei')
				);
				$instrument = $this->Mml->Instrument->find(array('Instrument.id'=>1));
			}else{
				$query = $this->params['url']['q'];	// クエリを解凍
				$query = base64_decode($query);	// base64デコード
				$query = gzinflate($query);	// zip解凍
				list($inst, $ch1, $ch2, $ch3) = split(';',$query);	// 解凍したデーターを分割
				$mml = array('Mml'=>array('ch1'=>$ch1,'ch2'=>$ch2,'ch3'=>$ch3,'pan'=>64,'nocache'=>true),'Article'=>array('title'=>'Lorelei Web Composer Output'),'User'=>array('username'=>'Lorelei'));
				$instrument = $this->Mml->Instrument->find(array('Instrument.id'=>$inst));
			}
			$this->set('mml', array_merge($mml,$instrument));
			$this->render('midi');
		}else{
			$this->pageTitle =__('Web MML Composing tool',true);
			$this->set('instruments', $this->Mml->Instrument->find('list'));
			$this->set('ranks', $this->Mml->Rank->find('list'));
		}
	}

/*************************************************************************************************/
}
?>